package mall

import (
	"fmt"
	"time"

	"gorm.io/gorm"
	"main.go/global"
	"main.go/model/mall"
	mallReq "main.go/model/mall/request"
	"main.go/utils"
)

//@author: [piexlmax](https://github.com/piexlmax)
//@function: Register
//@description: 用户注册
//@param: u model.SysUser
//@return: userInter system.SysUser, err error

type GoodsCategoryService struct{}

func (s *GoodsCategoryService) Create(u *mall.MallGoodsCategory) (out *mall.MallGoodsCategory, err error) {
	err = global.EVA_DB.Create(&u).Error
	return u, err
}

func (s *GoodsCategoryService) Delete(id int) (err error) {
	// 事务
	return global.EVA_DB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Where("id = ?", id).Delete(&mall.MallGoodsCategory{}).Error; err != nil {
			return err
		}
		return nil
	})
}

func (s *GoodsCategoryService) Update(req *mall.MallGoodsCategory) (out *mall.MallGoodsCategory, err error) {
	updateData := make(map[string]interface{})
	if len(req.Name) > 0 {
		updateData["name"] = req.Name
	}
	if req.Rank != 0 {
		updateData["rank"] = req.Rank
	}

	err = global.EVA_DB.Model(&mall.MallGoodsCategory{}).Where(mall.MallGoodsCategory{
		EVA_MODEL: global.EVA_MODEL{
			ID: req.ID,
		},
	}).Updates(updateData).Error
	return out, err
}

func (s *GoodsCategoryService) List(req *mallReq.MallGoodsCategoryListReq) (list []*mall.MallGoodsCategory, total int64, err error) {
	limit := req.PageSize
	offset := req.PageSize * (req.Page - 1)
	fmt.Println(limit, offset)
	db := global.EVA_DB.Model(&mall.MallGoodsCategory{})
	// 如果有条件搜索 下方会自动创建搜索语句
	if len(req.Name) != 0 {
		db = db.Where("name LIKE ?", "%"+req.Name+"%")
	}

	if req.ID != 0 {
		db = db.Where("id = ?", req.ID)
	}

	if req.StartCreatedAt != 0 && req.EndCreatedAt != 0 {
		t1 := time.Unix(req.StartCreatedAt, 0).In(utils.ShLocation)
		t2 := time.Unix(req.EndCreatedAt, 0).In(utils.ShLocation)
		db = db.Where("created_at BETWEEN ? AND ?", t1, t2)
	}
	err = db.Count(&total).Error
	if err != nil {
		return list, total, err
	}

	err = db.Order("id desc").Limit(limit).Offset(offset).Find(&list).Error
	return list, total, err
}

func (s *GoodsCategoryService) IsExistID(id uint) (data mall.MallGoodsCategory, err error) {
	err = global.EVA_DB.Model(&mall.MallGoodsCategory{}).Where("id=?", id).First(&data).Error
	return data, err
}
